package com.yz.group5.med_booking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yz.group5.med_booking.entity.Registration;
import com.yz.group5.med_booking.mapper.RegistrationMapper;
import com.yz.group5.med_booking.service.RegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegistrationServicelmpl extends ServiceImpl<RegistrationMapper, Registration> implements RegistrationService {

    @Autowired
    private RegistrationMapper registrationMapper;

    /**
     * 分页查询挂号列表
     * @param page 页码
     * @param pageSize 每页条数
     * @param keyword 搜索关键词
     * @param status 状态筛选
     * @return 分页结果
     */
    @Override
    public Map<String, Object> getPageList(Integer page, Integer pageSize, String keyword, Integer status) {
        // 创建分页对象
        Page<Registration> pagination = new Page<>(page, pageSize);

        // 构建查询条件
        QueryWrapper<Registration> queryWrapper = new QueryWrapper<>();

        // 关键词搜索（匹配患者ID或排班ID）
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                    .like("patient_id", keyword.trim())
                    .or()
                    .like("schedule_id", keyword.trim())
            );
        }

        // 状态筛选
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        // 按创建时间升序排序（确保排队顺序正确）
        queryWrapper.orderByAsc("created_at");

        // 执行分页查询
        IPage<Registration> resultPage = registrationMapper.selectPage(pagination, queryWrapper);

        // 封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", resultPage.getRecords());  // 当前页数据
        result.put("total", resultPage.getTotal());      // 总条数
        result.put("pages", resultPage.getPages());      // 总页数
        result.put("current", resultPage.getCurrent());  // 当前页码
        result.put("size", resultPage.getSize());        // 每页条数

        return result;
    }

    /**
     * 获取各状态的统计数据
     * @return 状态统计map
     */
    @Override
    public Map<String, Integer> getStatusCounters() {
        Map<String, Integer> counters = new HashMap<>(4);

        // 初始化统计数据
        counters.put("pending", 0);      // 预约中(1)
        counters.put("completed", 0);    // 已就诊(2)
        counters.put("cancelled", 0);    // 已取消(3)
        counters.put("noShow", 0);       // 爽约(4)

        // 查询所有状态的数量
        List<Map<String, Object>> statusList = registrationMapper.selectMaps(new QueryWrapper<Registration>()
                .select("status, count(*) as count")
                .groupBy("status")
        );

        // 填充统计数据
        for (Map<String, Object> item : statusList) {
            Integer status = (Integer) item.get("status");
            Integer count = ((Number) item.get("count")).intValue();

            switch (status) {
                case 1:
                    counters.put("pending", count);
                    break;
                case 2:
                    counters.put("completed", count);
                    break;
                case 3:
                    counters.put("cancelled", count);
                    break;
                case 4:
                    counters.put("noShow", count);
                    break;
            }
        }

        return counters;
    }

    /**
     * 开始就诊
     * @param id 挂号记录ID
     * @return 操作结果
     */
    @Override
    public boolean startVisit(Integer id) {
        if (id == null) {
            return false;
        }

        Registration registration = getById(id);
        if (registration == null) {
            return false;
        }

        // 只有"预约中"状态可以开始就诊
        if (registration.getStatus() != 1) {
            return false;
        }

        // 实际业务中可在此处添加开始时间等信息
        return true;
    }

    /**
     * 完成就诊
     * @param id 挂号记录ID
     * @return 操作结果
     */
    @Override
    public boolean completeVisit(Integer id) {
        if (id == null) {
            return false;
        }

        Registration registration = getById(id);
        if (registration == null) {
            return false;
        }

        // 更新状态为"已就诊"
        registration.setStatus(2);
        return updateById(registration);
    }

    /**
     * 取消就诊
     * @param id 挂号记录ID
     * @return 操作结果
     */
    @Override
    public boolean cancelVisit(Integer id) {
        if (id == null) {
            return false;
        }

        Registration registration = getById(id);
        if (registration == null) {
            return false;
        }

        // 更新状态为"已取消"
        registration.setStatus(3);
        return updateById(registration);
    }

    /**
     * 标记爽约
     * @param id 挂号记录ID
     * @return 操作结果
     */
    @Override
    public boolean markAsNoShow(Integer id) {
        if (id == null) {
            return false;
        }

        Registration registration = getById(id);
        if (registration == null) {
            return false;
        }

        // 更新状态为"爽约"
        registration.setStatus(4);
        return updateById(registration);
    }
}
